<template>
  <div  class="treeContainer">
    <div class="topBox">
      <p class="title">使用antd折叠树组件实现折叠和拖拽</p>
      <p class="subTitle">介绍：基于vue3+vite+antd</p>
      <p class="subTitle">作者：栗xx</p>
    </div>
    <!-- 固定在目标节点上的提示框 -->
    <a-tree
      ref="treeRef"
      :show-line="showLine"
      :default-expanded-keys="['0-0-0']"
      :tree-data="treeData"
      @select="onSelect"
      draggable
      checkable
      @dragstart="onDragStart"
      @dragenter="onDragEnter"
      @dragleave="onDragLeave"
      @drop="onDrop"
      @dragover="onDragOver"
    >
      <template #title="{ dataRef }">
        <a-tooltip 
          :title="nodeTooltipText" 
          :visible="hoverNodeKey === dataRef.key"
          placement="right"
          :color="nodeTooltipColor"
        >
          <span class="tree-node-title">{{ dataRef.title }}</span>
        </a-tooltip>
      </template>
      <template #title1="{ key, title1 }">
        <div class="tree-node-content" :data-node-key="key">
          <span>{{ title1 || `节点 ${key}` }}</span>
          <span v-if="mergedNodes[key]?.length" class="merged-count">
            (已合并: {{ mergedNodes[key].length }})
          </span>
        </div>
      </template>
    </a-tree>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick,onMounted } from 'vue';
import { 
  CarryOutOutlined, 
  SmileTwoTone
} from '@ant-design/icons-vue';
import type { TreeProps } from 'ant-design-vue';
import axios from 'axios'; 
// 树数据（响应式）
const treeData = ref([]);
// 初始化加载数据
onMounted(() => {
  fetchTreeData()
});
const fetchTreeData = async () => {
  try {
    const res = await axios.get('/api/tree-data',
    {params: {
        _t: Date.now() // 或 Math.random()
      }
    });
    treeData.value = res.data.data.tree.map(item => ({
      ...item,
      // AntD Tree 需要 isLeaf 标识叶子节点
      isLeaf: !item.children || item.children.length === 0
    }));
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};
const showLine = ref(true);
const showIcon = ref(false);
const treeRef = ref();
const tooltipAnchor = ref();

// 拖拽相关状态
const currentDragNode = ref<any>(null);
const currentHoverNode = ref<any>(null);
const dropPosition = ref<number>(-1);

// 节点提示框状态
const nodeTooltipVisible = ref(false);
const nodeTooltipText = ref('');
const nodeTooltipColor = ref('#1677ff');
const hoverNodeKey = ref('');

// 记录合并的节点
const mergedNodes = ref<Record<string, Array<{key: string, title?: string}>>>({});

// const treeData = ref<TreeProps['treeData']>([
//   {
//     title: 'parent 1',
//     key: '0-0',
//     children: [
//       {
//         title: 'parent 1-0',
//         key: '0-0-0',
//         children: [
//           { title: 'leaf', key: '0-0-0-0' },
//           { title: 'leaf111',key: '0-0-0-1' },
//           { title: 'leaf', key: '0-0-0-2' },
//         ],
//       },
//       {
//         title: 'parent 1-1',
//         key: '0-0-1',
//         children: [{ title: 'leaf', key: '0-0-1-0' }],
//       },
//       {
//         title: 'parent 1-2',
//         key: '0-0-2',
//         children: [
//           { title: 'leaf 1', key: '0-0-2-0' },
//           { title: 'leaf 2', key: '0-0-2-1' },
//         ],
//       },
//     ],
//   },
//   {
//     title: 'parent 2',
//     key: '0-1',
//     children: [
//       {
//         title: 'parent 2-0',
//         key: '0-1-0',
//         children: [
//           { title: 'leaf', key: '0-1-0-0' },
//           { title: 'leaf', key: '0-1-0-1' },
//         ],
//       },
//     ],
//   },
// ]);

const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
  console.log('selected', selectedKeys, info);
};

const getPopupContainer = () => {
  return tooltipAnchor.value?.parentNode || document.body;
};

// 更新Tooltip位置到当前悬停节点
const updateTooltipPosition = (node: any) => {
  if (!node || !treeRef.value) return;
  
  nextTick(() => {
    const nodeElement = document.querySelector(`[data-node-key="${node.key}"]`);
    if (nodeElement && tooltipAnchor.value) {
      const rect = nodeElement.getBoundingClientRect();
      tooltipAnchor.value.style.left = `${rect.left + rect.width / 2}px`;
      tooltipAnchor.value.style.top = `${rect.top}px`;
    }
  });
};

// 查找节点父级和索引
const findNodeParentAndIndex = (data: any[], key: string) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    if (node.key === key) {
      return { parent: data, index: i };
    }
    if (node.children) {
      const result = findNodeParentAndIndex(node.children, key);
      if (result) return result;
    }
  }
  return null;
};

// 拖拽开始
const onDragStart = (info: any) => {
  currentDragNode.value = info.node;
};

// 拖拽进入节点
const onDragEnter = (info: any) => {
  currentHoverNode.value = info.node;
  dropPosition.value = info.dropPosition;
  hoverNodeKey.value = info.node.key;
  updateTooltipPosition(info.node);
  updateDragTooltip(info.node, info.dropPosition);
};

// 拖拽离开节点
const onDragLeave = () => {
  currentHoverNode.value = null;
  nodeTooltipVisible.value = false;
};

// 拖拽悬停在节点上
const onDragOver = (info: any) => {
  if (currentHoverNode.value && currentHoverNode.value.key === info.node.key) {
    dropPosition.value = info.dropPosition;
    updateTooltipPosition(info.node);
    updateDragTooltip(info.node, info.dropPosition);
  }
};

// 更新拖拽提示信息
const updateDragTooltip = (dropNode: any, position: number) => {
  if (!currentDragNode.value || !dropNode) {
    nodeTooltipVisible.value = false;
    return;
  }

  // 不能拖拽到自身
  if (currentDragNode.value.key === dropNode.key) {
    nodeTooltipVisible.value = false;
    return;
  }

  // 获取两个节点的层级路径
  const dragPath = currentDragNode.value.pos.split('-');
  const dropPath = dropNode.pos.split('-');
  
  // 确保是同一层级（父节点相同）
  const dragParentPath = dragPath.slice(0, -1).join('-');
  const dropParentPath = dropPath.slice(0, -1).join('-');
  
  // // 如果不是同一父节点下，显示错误提示
  // if (dragParentPath !== dropParentPath) {
  //   nodeTooltipText.value = '不能跨级别移动！';
  //   nodeTooltipColor.value = '#ff4d4f';
  //   nodeTooltipVisible.value = true;
  //   return;
  // }

  // 根据位置显示不同的提示信息
  if (position === 0) {
    nodeTooltipText.value = `将合并到 ${dropNode.title || '节点'}`;
    nodeTooltipColor.value = '#1677ff';
  } else if (position === -1) {
    nodeTooltipText.value = `将放置在 ${dropNode.title || '节点'} 上方`;
    nodeTooltipColor.value = '#1677ff';
  } else {
    nodeTooltipText.value = `将放置在 ${dropNode.title || '节点'} 下方`;
    nodeTooltipColor.value = '#1677ff';
  }
  
  nodeTooltipVisible.value = true;
};

const onDrop = (info: any) => {
  const { dragNode, node: dropNode, dropPosition } = info;

  // 验证层级
  const dragPath = dragNode.pos.split('-');
  const dropPath = dropNode.pos.split('-');
  const dragParentPath = dragPath.slice(0, -1).join('-');
  const dropParentPath = dropPath.slice(0, -1).join('-');
  
  if (dragParentPath !== dropParentPath) {
    return;
  }

  // 深拷贝树数据
  const newTreeData = JSON.parse(JSON.stringify(treeData.value));
  const newMergedNodes = { ...mergedNodes.value };

  // 查找拖拽节点
  const dragResult = findNodeParentAndIndex(newTreeData, dragNode.key);
  if (!dragResult) {
    return;
  }

  // 合并操作
  if (dropPosition === 0) {
    const dropResult = findNodeParentAndIndex(newTreeData, dropNode.key);
    if (!dropResult) {
      return;
    }

    const [movedNode] = dragResult.parent.splice(dragResult.index, 1);
    
    if (!newMergedNodes[dropNode.key]) {
      newMergedNodes[dropNode.key] = [];
    }
    newMergedNodes[dropNode.key].push({
      key: movedNode.key,
      title: movedNode.title || `节点 ${movedNode.key}`
    });

    if (!dropResult.parent[dropResult.index].children) {
      dropResult.parent[dropResult.index].children = [];
    }

    dropResult.parent[dropResult.index].children.push(movedNode);
  } 
  // 移动操作
  else {
    const dropResult = findNodeParentAndIndex(newTreeData, dropNode.key);
    if (!dropResult) {
      return;
    }

    const [movedNode] = dragResult.parent.splice(dragResult.index, 1);
    let newIndex = dropResult.index;
    
    if (dropPosition !== -1) {
      newIndex += 1;
    }
    
    dragResult.parent.splice(newIndex, 0, movedNode);
  }

  // 更新数据
  treeData.value = newTreeData;
  mergedNodes.value = newMergedNodes;
  
  // 重置拖拽状态
  currentDragNode.value = null;
  currentHoverNode.value = null;
  nodeTooltipVisible.value = false;
};
</script>

<style scoped>
.tree-node-content {
  display: inline-flex;
  align-items: center;
  padding: 2px 0;
  cursor: pointer;
}

.merged-count {
  margin-left: 8px;
  font-size: 12px;
  color: #888;
}

/* 多行标题的特殊处理 */
:deep(.ant-tree-node-content-wrapper) .ant-tree-title {
  white-space: normal;
}

/* 隐藏Tooltip锚点元素 */
[ref="tooltipAnchor"] {
  display: none;
}

/* 确保拖拽提示在最上层 */
:deep(.ant-tooltip) {
  z-index: 9999;
}

:deep(.ant-tooltip-inner) {
  font-size: 14px;
  padding: 8px 12px;
  max-width: 300px;
  white-space: nowrap;
}
</style>
<style lang="less" scoped>
.treeContainer{
  background:#fff;
  font-size: 14px;
  font-family: PingFangSC-Semibold, PingFang SC;
  .topBox{
    border-bottom:2px solid #f2f2f2;
    margin-bottom:20px;
    .title{
      font-size:18px;
      color:#333333;
      text-align: left;
    }
    .subTitle{
      text-align:left;
    }
  }

}

</style>